import tool from '@/utils/tool'
import { onBeforeRouteLeave } from 'vue-router'

export default function (key, excludeNames) {
	onBeforeMount(() => {
		window.addEventListener('beforeunload', remove)
	})
	onBeforeUnmount(() => {
		window.removeEventListener('beforeunload', remove)
	})
	onBeforeRouteLeave((to, from, next) => {
		if (!excludeNames.includes(to.name)) {
			remove()
		}
		next()
	})

	const get = () => {
		return tool.session.get(key)
	}

	const set = (value) => {
		const tableFilter = get(key) || {}
		tableFilter[key] = value
		tool.session.set(key, value)
	}

	const remove = () => {
		tool.session.remove(key)
	}

	return {
		get,
		set,
		remove
	}
}
